// Dependencies

var $ = require('./zepto.base.js');
var fs = require('fs');
var path = require('path');
var url = require('url');
var http = require('http');
var jdreact = require('../js/jdreact.js');
var utility = require('./utility.js');
var doJdReactLogin = require('../js/jdreact-login').doJdReactLogin;
var file = require('./file.js');
var color = require('./colors-cli/lib/index.js');


function download(options) {
	options || (options={});
	var save_to_filepath = options.save_to_filepath;
	return $.Deferred(function (d) {

		if((!options.so_bundle_url)||(!save_to_filepath)){
			var error_msg = '请指定文件url，以及下载文件的保存路径';
			console.log(error_msg);
			//return error_msg;
			return d.reject(error_msg);
		}

		//var success = (typeof options.success==='function') ? options.success : function () {};
		//var fail = (typeof options.fail==='function') ? options.fail : function () {};
		// var fillname_suffix = (typeof options.suffix==='function') ? options.suffix : null;



		var so_bundle_url = options.so_bundle_url;


		var file_name_from_url = url.parse(so_bundle_url).pathname.split('/').pop();
		// file_name形如： JDReactDaoJia1553496385.so ， 看下面if语句中正则
		if( (typeof file_name_from_url!=='string') || (!file_name_from_url.match(/^JDReact[a-zA-Z0-9_]+\d+\.so$/)) ){
			return d.reject('url中文件名与预期不一致');
		}

		if(fs.existsSync(save_to_filepath)){
			console.log(color.green('文件已存在'));
			var get_form_cache = true;
			return d.resolve(file_name_from_url,get_form_cache);
		} else {
			console.log('文件不存在，需要下载');
		}

		// if(typeof options.suffix==='function'){
		//
		// }
		// file_name = file_name.replace('.so','.zip');


		var file = fs.createWriteStream(options.save_to_filepath);

		http.get(so_bundle_url, function(res) {
			res.on('data', function(data) {
				file.write(data);
			}).on('end', function() {
				file.end();
				//success(downloaded_filepath);
				var get_form_cache = false;
				d.resolve(file_name_from_url,get_form_cache);
			});
		});
	});
}


// download({
// 	file_url:'http://storage.jd.com/bucket-1/JDReactDaoJia1553496385.so?Expires=3700980034&AccessKey=nxgRi4Ob6sX9G8IT&Signature=gd3qy7Uar7zmNNggqIh%2BLK%2FqnvE%3D&jdreactkey=JDReactDaoJia&jdreactmodule=JDReactDaoJia&jdreactapp=JDReactDaoJia',
// 	download_dir:'/Users/xx/Documents/htdocs/reactnative/Pure0554/DJReactNative/bundle/temp/'
// });

function make_sure_logged(has_logged) {
	return $.Deferred(function (d) {
		if(has_logged){
			return d.resolve();
		} else {
			doJdReactLogin().done(function (index_html) {

				jdreact.parsePackTarget(index_html);
				d.resolve();

			}).fail(function (error) {
				console.log('登录失败，检查：1.网络， 2.手动打开http://ci.jares.jd.com/jenkins/login?from=%2Fjenkins%2F查看是否可以登录')
				d.reject();
			});
		}
	});
}

// 判断temp/目录中是否已存在该文件，若存在，则不重复下载
function exist_target_zip_bundle(platform,id) {
	var folder_of_bundle = utility.get_dirname_of_bundle_folder();
	var temp_folder = path.join(folder_of_bundle,'temp/');
	var list = file.getAllFilepathInDirSync(temp_folder,function (fullpath,stat,filename) {
		if(filename.indexOf(platform+'_'+id+'_')===0){
			return true;
		}
	});
	if(list[0]){
		list[1] && console.log(color.red('存在2个同一id的包'));
		return list[0];
	} else {
		return false;
	}

}



function download_so_bundle(platform,id,has_logged,link_matcher) {
	return $.Deferred(function (d) {
		var folder_of_bundle = utility.get_dirname_of_bundle_folder();
		var save_to_folder = path.join(folder_of_bundle,'temp/');
		var save_to_filename_without_suffix = platform+'_'+id;
		var save_to_filename = save_to_filename_without_suffix+'.zip';
		var save_to_filepath = path.join(save_to_folder, save_to_filename);

		// if(exist_target_zip_bundle(platform,id)){
		// 	return d.resolve();
		// }

		make_sure_logged(has_logged).done(function () {
			jdreact.get_so_bundle_url_by_id(platform,id,link_matcher).done(function (so_bundle_url) {
				fs.mkdirSync(save_to_folder , {recursive:true});
				download({
					so_bundle_url:so_bundle_url,
					save_to_filepath:save_to_filepath
				}).done(function (file_name_from_url,get_form_cache) {
					d.resolve(save_to_filename_without_suffix,save_to_filename,save_to_filepath,save_to_folder,get_form_cache,file_name_from_url);
				});

			}).fail(function (error) {
				error||(error={});
				const error_msg = '没有找到bundle的链接'+'\n'+error.console_url;
				console.log(error_msg);
				d.reject(error_msg);
			});
		}).fail(function () {
			d.reject('登陆失败');
		});

	});
}


// download_so_bundle('ios',4446);

module.exports = download_so_bundle;